package cn.sample.security.json.config;

import cn.sample.security.json.filter.JsonAuthenticationFilter;
import cn.sample.security.json.handler.JsonAuthenticationFailureHandler;
import cn.sample.security.json.handler.JsonAuthenticationSuccessHandler;
import cn.sample.security.provider.UsernamePasswordAuthenticationProvider;
import cn.sample.system.service.ResourceSupport;
import cn.sample.system.service.UserSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * <h2></h2>
 *
 * <p>JSON 认证配置</p>
 *
 * @author HKD
 */
@Slf4j
@Configuration
public class JsonAuthenticationConfig {

    @Resource
    private UserSupport userSupport;

    @Resource
    private ResourceSupport resourceSupport;

    @Resource
    private JsonAuthenticationFailureHandler jsonAuthenticationFailureHandler;

    @Resource
    private JsonAuthenticationSuccessHandler jsonAuthenticationSuccessHandler;

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * JSON 认证提供类
     */
    @Bean
    public UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider(){
        return new UsernamePasswordAuthenticationProvider(userSupport,resourceSupport,passwordEncoder());
    }

    /**
     * JSON 认证过滤器
     */
    @Bean
    public JsonAuthenticationFilter jsonAuthenticationFilter(){
        JsonAuthenticationFilter jsonAuthenticationFilter = new JsonAuthenticationFilter();
        // 配置认证管理器
        ProviderManager providerManager = new ProviderManager(usernamePasswordAuthenticationProvider());
        jsonAuthenticationFilter.setAuthenticationManager(providerManager);
        // 认证成功处理器
        jsonAuthenticationFilter.setAuthenticationSuccessHandler(jsonAuthenticationSuccessHandler);
        // 认证失败处理器
        jsonAuthenticationFilter.setAuthenticationFailureHandler(jsonAuthenticationFailureHandler);
        return jsonAuthenticationFilter;
    }


}
